﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InstituteManager.Bussiness;
using InstituteManager.Data;
using System.Security.Cryptography;
using System.IO;

namespace InstituteManager.adm
{
    public partial class Posting : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // hide message            
            pnlMessage.Visible = false;
            if (!IsPostBack)
            {
                lbtDeleteT.Attributes.Add("onClick", "javascript:return confirm(\"Are you sure ?\")");
                lbtDeleteB.Attributes.Add("onClick", "javascript:return confirm(\"Are you sure ?\")");
                gridBind();
            }
        }

        protected void GeneralDateControls(DropDownList ddlDay, DropDownList ddlMon, DropDownList ddlYear)
        {
            for (int i = 1; i <= 31; i++)
                ddlDay.Items.Add(new ListItem(i + "", i + ""));
            for (int i = 1; i <= 12; i++)
                ddlMon.Items.Add(new ListItem(i + "", i + ""));
            for (int i = 1900; i <= DateTime.Now.Year; i++)
                ddlYear.Items.Add(new ListItem(i + "", i + ""));
        }

        protected string getMarkString(object Mark)
        {
            if (Mark == null)
                return "";
            switch (int.Parse(Mark.ToString()))
            {
                case 1:
                    return "Best";
                case 2:
                    return "Better";
                case 3:
                    return "Good";
                case 4:
                    return "Moderate";
                case 5:
                    return "Normal";
                case 6:
                    return "Disqualified";
            }
            return "";
        }

        protected void gridBind()
        {
            grvView.DataSource = PostingBL.getByAll();
            grvView.DataBind();

            ddlCompetitionId.DataSource = CompetitionBL.getUpcomming();
            ddlCompetitionId.DataTextField = "CompetitionName";
            ddlCompetitionId.DataValueField = "CompetitionId";
            ddlCompetitionId.DataBind();
            ddlCompetitionId.Items.Insert(0, new ListItem("Choice Competition", "0"));
        }

        protected string getCompetitionName(string PostingId)
        {
            if (PostingBL.getById(int.Parse(PostingId)).tbl_Competition != null)
                return PostingBL.getById(int.Parse(PostingId)).tbl_Competition.CompetitionName + "&nbsp;&nbsp;&nbsp;";
            return "";
        }

        protected bool IsCompetitionExpired(string PostingId)
        {
            if (PostingBL.getById(int.Parse(PostingId)).tbl_Competition != null)
                return CompetitionBL.isExpired(PostingBL.getById(int.Parse(PostingId)).tbl_Competition.CompetitionId);
            return false;
        }

        public string GetMD5(string chuoi)
        {
            string str_md5 = "";
            byte[] mang = System.Text.Encoding.UTF8.GetBytes(chuoi);

            MD5CryptoServiceProvider my_md5 = new MD5CryptoServiceProvider();
            mang = my_md5.ComputeHash(mang);

            foreach (byte b in mang)
            {
                str_md5 += b.ToString("X2").ToLower();
            }

            return str_md5;
        }


        protected void ResetControl()
        {
            txtId.Text = "";

            txtPostingName.Text = "";
            txtDescription.Text = "";
            txtPrice.Text = "";

            ddlCompetitionId.SelectedIndex = 0;
        }

        protected void grvView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
                ((CheckBox)e.Row.FindControl("chkSelectAll")).Attributes.Add("onClick", "SelectAllClick(this)");
            if (e.Row.RowType == DataControlRowType.DataRow)
                ((CheckBox)e.Row.FindControl("chkSelect")).Attributes.Add("onClick", "SelectClick(this)");
        }

        protected void lbtAddnew_Click(object sender, EventArgs e)
        {
            pnlView.Visible = false;
            pnlUpdate.Visible = true;

            ResetControl();
        }

        protected void lbtBack_Click(object sender, EventArgs e)
        {
            pnlView.Visible = true;
            pnlUpdate.Visible = false;
        }

        protected void lbtSave_Click(object sender, EventArgs e)
        {
            string strId = txtId.Text;

            Data.tbl_Posting entt = new Data.tbl_Posting();
            entt.PostingName = txtPostingName.Text;

            if (ddlCompetitionId.SelectedIndex > 0)
            {
                entt.PostDate = DateTime.Now;
            }
            
            entt.Description = txtDescription.Text;
            if (txtPrice.Text.Trim().Length > 0)
                entt.Price = int.Parse( txtPrice.Text);
            if (fudImageURL.HasFile)
            {
                if (!Directory.Exists(Server.MapPath("~/images/posting/") + Session["Username"]))
                    Directory.CreateDirectory(Server.MapPath("~/images/posting/") + Session["Username"] );

                if (File.Exists(Server.MapPath("~/images/posting/") + Session["Username"] + "/" + fudImageURL.FileName))
                    File.Delete(Server.MapPath("~/images/posting/") + Session["Username"] + "/" + fudImageURL.FileName);                

                fudImageURL.SaveAs(Server.MapPath("~/images/posting/") + Session["Username"] + "/" + fudImageURL.FileName);
                entt.ImageUrl = "~/images/posting/" + Session["Username"] + "/" + fudImageURL.FileName;
            }

            // if strId = "" then add new else update
            if (strId.Trim() == "")
            {
                if (entt.ImageUrl == null)
                {
                    ShowMessage(-1,"You need to choice a picture !");
                    return;
                }
                if (PostingBL.AddNew(entt,int.Parse( ddlCompetitionId.SelectedValue), Session["Username"].ToString()))
                {
                    ShowMessage(1, "Data added successfully ! ");
                    gridBind();
                }
                else
                {
                    ShowMessage(0, "Data added fail : " + PostingBL.errorMsg);
                }
            }
            else
            {
                entt.PostingId = int.Parse(strId);
                if (PostingBL.Update(entt, int.Parse(ddlCompetitionId.SelectedValue)))
                {
                    ShowMessage(1, "Data updated successfully ! ");
                    gridBind();
                }
                else
                {
                    ShowMessage(0, "Data updated fail : " + PostingBL.errorMsg);
                }
            }

            pnlView.Visible = true;
            pnlUpdate.Visible = false;
            gridBind();
        }


        protected void ShowMessage(int MegType, string Message)
        {
            pnlMessage.Visible = true;
            ((Label)pnlMessage.FindControl("lblMessage")).Text = Message;
            switch (MegType)
            {
                case 1:
                    pnlMessage.CssClass = "sukses";
                    break;
                case 0:
                    pnlMessage.CssClass = "gagal";
                    break;
                default:
                    pnlMessage.CssClass = "informasi";
                    break;
            }
        }

        protected void grvView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvView.PageIndex = e.NewPageIndex;
            gridBind();
        }

        protected void grvView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strId = e.CommandArgument.ToString();
            Data.tbl_Posting obj = new tbl_Posting();
            switch (e.CommandName)
            {
                case "cmdEdit":
                    txtId.Text = strId;
                    obj = PostingBL.getById(int.Parse(strId));
                    txtPostingName.Text = obj.PostingName;

                    txtDescription.Text = obj.Description;
                    txtPrice.Text = obj.Price.ToString();

                    if (obj.tbl_Competition != null)
                        if (! CompetitionBL.isExpired(obj.tbl_Competition.CompetitionId))
                            ddlCompetitionId.SelectedValue = obj.tbl_Competition.CompetitionId.ToString();
                        else
                        {
                            ShowMessage(0, "You can't edit this posting. The competition is expired !");
                            return;
                        }

                    pnlUpdate.Visible = true;
                    pnlView.Visible = false;
                    // hide controls password.

                    break;
                case "cmdView":
                    obj = PostingBL.getById(int.Parse(strId));
                    lblPostingName.Text = obj.PostingName;
                    if (obj.PostDate != null)
                        lblPostDate.Text = obj.PostDate.Value.ToString("d");
                    lblDescription.Text = obj.Description;
                    lblPrice.Text = obj.Price.ToString();
                    if (obj.tbl_Competition != null)
                        lblCompetitionName.Text = obj.tbl_Competition.CompetitionName;
                    
                    switch (obj.Mark){
                        case 1:
                            lblMark.Text = "Best";
                            break;
                        case 2:
                            lblMark.Text = "Better";
                            break;
                        case 3:
                            lblMark.Text = "Good";
                            break;
                        case 4:
                            lblMark.Text = "Moderate";
                            break;
                        case 5:
                            lblMark.Text = "Normal";
                            break;
                        case 6:
                            lblMark.Text = "Disqualified";
                            break;
                        default:
                            lblMark.Text = "";
                            break;
                    }
                    lblRemark.Text = obj.Remark;
                    imgImage.ImageUrl = obj.ImageUrl;

                    pnlView.Visible = false;
                    pnlDetail.Visible = true;
                    break;
                case "cmdDelete":
                    if (CompetitionBL.isExpired(int.Parse(strId)))
                    {
                        ShowMessage(0, "Competition is expired ! You can't delete it !");
                        return;
                    }
                    if (PostingBL.Delete(int.Parse(strId)))
                    {                        
                        ShowMessage(1, "Data deleted successfully ! ");
                        gridBind();
                    }
                    else
                    {
                        ShowMessage(0, "Data deleted fail : " + PostingBL.errorMsg);
                    }
                    break;
            }
        }

        protected void lbtRefresh_Click(object sender, EventArgs e)
        {
            gridBind();
        }

        protected void lbtDelete_Click(object sender, EventArgs e)
        {
            bool result = true;
            bool isChecked = false;
            foreach (GridViewRow row in grvView.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    if (((CheckBox)row.FindControl("chkSelect")).Checked == true)
                    {
                        isChecked = true;
                        if (!PostingBL.Delete(int.Parse(grvView.DataKeys[row.RowIndex].Value.ToString())))
                            result = false;
                    }
                }
            }

            if (isChecked == false)
                ShowMessage(-1, "You have not selected data to delete ! ");
            else if (result)
            {
                ShowMessage(1, "Data deleted successfully ! ");
                gridBind();
            }
            else
            {
                ShowMessage(0, "Data deleted fail : " + PostingBL.errorMsg);
            }
        }

        protected void ibtSearch_Click(object sender, ImageClickEventArgs e)
        {
            grvView.DataSource = PostingBL.SearchByName(txtSearch.Text);
            DataBind();
        }

        protected void lbtBackDetail_Click(object sender, EventArgs e)
        {
            pnlDetail.Visible = false;
            pnlView.Visible = true;
        }
    }
}